/*
 * @lc app=leetcode.cn id=2105 lang=typescript
 *
 * [2105] 给植物浇水 II
 */

// @lc code=start
function minimumRefill(plants: number[], capacityA: number, capacityB: number): number {
  const n = plants.length;
  // 双指针
  let i = 0;
  let j = n - 1;
  // 水量
  let capA = capacityA;
  let capB = capacityB;
  // 结果
  let res = 0;

  // 双指针遍历
  while (i < j) {
    if (plants[i] > capA) {
      capA = capacityA;
      res++;
    }
    capA -= plants[i];
    i++;

    if (plants[j] > capB) {
      capB = capacityB;
      res++;
    }
    capB -= plants[j];
    j--;
  }

  if (i === j) {
    if (plants[i] > capA && plants[i] > capB) {
      res++;
    }
  }

  return res;
}
// @lc code=end
